package com.wqz.taco_cloud_jpa.controller;

import com.wqz.taco_cloud_jpa.impl.IngredientRepository;
import com.wqz.taco_cloud_jpa.impl.OrderRepository;
import com.wqz.taco_cloud_jpa.impl.TacoRepository;
import com.wqz.taco_cloud_jpa.models.Ingredient;
import com.wqz.taco_cloud_jpa.models.Order;
import com.wqz.taco_cloud_jpa.models.Taco;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/design")
@SessionAttributes("order")
public class DesignController {
    private final IngredientRepository ingredientRepository;
    private final TacoRepository tacoRepository;
    private final OrderRepository orderRepository;

    @Autowired
    public DesignController(IngredientRepository ingredientRepository, TacoRepository tacoRepository, OrderRepository orderRepository) {
        this.ingredientRepository = ingredientRepository;
        this.orderRepository = orderRepository;
        this.tacoRepository = tacoRepository;
    }

    @ModelAttribute(name="design")
    public Taco design() {
        log.info("生成一个新taco");
        return new Taco();
    }

    @ModelAttribute(name="order")
    public Order order() {
        log.info("生成一个新order");
        return new Order();
    }

    @GetMapping
    public String showDesignForm(Model model ) {
        List<Ingredient> ingredients = new ArrayList<>();
        ingredientRepository.findAll().forEach(ingredients::add);

        for (Ingredient.Type type : Ingredient.Type.values()) {
            log.info("type is %s", type.toString());
            model.addAttribute(type.toString().toLowerCase(), filterByType(ingredients,type));
        }

        return "design";
    }

    private List<Ingredient> filterByType(List<Ingredient> ingredients, Ingredient.Type type) {
        return ingredients
                .stream()
                .filter(x -> x.getType().equals(type))
                .collect(Collectors.toList());
    }

    /**
     * Order对象为参数，且@ModelAttribute注解能够确保会在model中创建一个Order对象
     * 处理design页面的点击button的post请求
     * @param design
     * @param errors
     * @param order
     * @return
     */
    @PostMapping
    public String processDesignForm(@Valid Taco design, Errors errors, @ModelAttribute Order order) {
        if (errors.hasErrors()) {
            log.info("error occurred in submit button");
            return "/design";
        }

        log.info("processing design: " + design);
        // 这里这样写会直接报错
        Taco saved = tacoRepository.save(design);
        order.addDesign(saved);

        return "redirect:/order/current";
    }

}
